package org.jeecg.modules.qy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.netty.util.internal.MathUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.qy.entity.QyCommodityMarketing;
import org.jeecg.modules.qy.entity.QyMarketing;
import org.jeecg.modules.qy.service.IQyCommodityMarketingService;
import org.jeecg.modules.qy.service.IQyMarketingReceiveService;
import org.jeecg.modules.qy.service.IQyMarketingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 营销管理
 * @Author: jeecg-boot
 * @Date:   2021-03-11
 * @Version: V1.0
 */
@Api(tags="营销管理")
@RestController
@RequestMapping("/qy/qyMarketing")
@Slf4j
public class QyMarketingController extends JeecgController<QyMarketing, IQyMarketingService> {
	@Autowired
	private IQyMarketingService qyMarketingService;

	@Autowired
	private IQyMarketingReceiveService marketingReceiveService;

	@Autowired
	private IQyCommodityMarketingService qyCommodityMarketingService;
	
	/**
	 * 分页列表查询
	 *
	 * @param qyMarketing
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "营销管理-分页列表查询")
	@ApiOperation(value="营销管理-分页列表查询", notes="营销管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(QyMarketing qyMarketing,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<QyMarketing> queryWrapper = QueryGenerator.initQueryWrapper(qyMarketing, req.getParameterMap());
		Page<QyMarketing> page = new Page<QyMarketing>(pageNo, pageSize);
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		queryWrapper.eq("company_id",loginUser.getCompanyId());
		IPage<QyMarketing> pageList = qyMarketingService.page(page, queryWrapper);
		if(CollectionUtils.isNotEmpty(pageList.getRecords())){
			for(QyMarketing marketing:pageList.getRecords()){
				//查询出参与人数 与使用个数
				marketing.setJoinPerson(marketingReceiveService.getJoinPerson(marketing.getId()));
				marketing.setUseNum(marketingReceiveService.getuserNum(marketing.getId()));
				marketing.setReceiveMoney(marketingReceiveService.getReceiveMoney(marketing.getId()));
				if(marketing.getActivityType()==2){
					//固定金额计算总红包金额
					marketing.setTotalMoney(marketing.getSingleMoney()*marketing.getNum());
					//计算剩余金额
					marketing.setSurplusMoney(marketing.getTotalMoney()-marketing.getReceiveMoney());
				}
				marketing.setUnUseNum(marketing.getJoinPerson()-marketing.getUseNum());//未使用量
				marketing.setUseNumStr(marketing.getUseNum()+"/"+marketing.getUnUseNum());//使用情况
			}
		}
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param qyMarketing
	 * @return
	 */
	@AutoLog(value = "营销管理-添加")
	@ApiOperation(value="营销管理-添加", notes="营销管理-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody QyMarketing qyMarketing) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(StringUtils.isEmpty(loginUser.getCompanyId())){
			return Result.ERROR("无权限添加营销活动");
		}
		qyMarketing.setCompanyId(loginUser.getCompanyId());
		qyMarketing.setActivityStatus(0);
		qyMarketing.setUseNum(0);
		qyMarketing.setJoinPerson(0);
		qyMarketingService.save(qyMarketing);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param qyMarketing
	 * @return
	 */
	@AutoLog(value = "营销管理-编辑")
	@ApiOperation(value="营销管理-编辑", notes="营销管理-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody QyMarketing qyMarketing) {
		qyMarketingService.updateById(qyMarketing);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "营销管理-通过id删除")
	@ApiOperation(value="营销管理-通过id删除", notes="营销管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		if(marketingReceiveService.getJoinPerson(id)>0){
			return Result.error("该营销活动已经被领取，无法删除");
		}
		qyMarketingService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	/*@AutoLog(value = "营销管理-批量删除")
	@ApiOperation(value="营销管理-批量删除", notes="营销管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.qyMarketingService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}*/
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "营销管理-通过id查询")
	@ApiOperation(value="营销管理-通过id查询", notes="营销管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		QyMarketing qyMarketing = qyMarketingService.getById(id);
		if(qyMarketing==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(qyMarketing);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param qyMarketing
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, QyMarketing qyMarketing) {
        return super.exportXls(request, qyMarketing, QyMarketing.class, "营销管理");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, QyMarketing.class);
    }


	 /**
	  *   通过id停用 启用
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "营销管理-通过id停用 启用")
	 @ApiOperation(value="营销管理-通过id停用 启用", notes="营销管理-通过id停用 启用")
	 @GetMapping(value = "/updateStatus")
	 public Result<?> updateStatus(@RequestParam(name="id",required=true) String id,
							 @RequestParam(name="activityStatus",required=true) Integer activityStatus) {
		 QyMarketing qyMarketing = qyMarketingService.getById(id);
		 if(null == qyMarketing){
		 	return Result.error("参数错误");
		 }
		 qyMarketing.setActivityStatus(activityStatus);
		 qyMarketingService.updateById(qyMarketing);
		 return Result.OK("操作成功!");
	 }

	 /**
	  * 查询已经启用的营销列表
	  *
	  * @param id
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "营销管理-列表查询")
	 @ApiOperation(value="营销管理-列表查询", notes="营销管理-列表查询")
	 @GetMapping(value = "/findMarketingList")
	 public Result<?> findMarketingList(@RequestParam(name="id",required=true) String id,
									HttpServletRequest req) {
		 QueryWrapper<QyMarketing> queryWrapper = new QueryWrapper<>();
		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 queryWrapper.eq("company_id",loginUser.getCompanyId());
		 queryWrapper.eq("activity_status",1);
		 queryWrapper.orderByDesc("create_time");
		 List<QyMarketing> pageList = qyMarketingService.list( queryWrapper);
		 QyCommodityMarketing qyCommodityMarketing = qyCommodityMarketingService.getByCommodityId(id);
		 Map<String,Object> map = new HashMap<>();
		 map.put("marketList",pageList);
		 map.put("commodityMarketing",qyCommodityMarketing);
		 return Result.OK(map);
	 }


}
